package com.zjl.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zjl.common.BaseContext;
import com.zjl.common.R;
import com.zjl.entity.ShoppingCart;
import com.zjl.mapper.ShoppingCartMapper;
import com.zjl.service.ShoppingCartService;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Service
public class ShoppingCartServiceImpl extends ServiceImpl<ShoppingCartMapper, ShoppingCart> implements ShoppingCartService {

    /**
     * 添加购物车
     * @return
     */
    @Override
    public ShoppingCart add(ShoppingCart shoppingCart) {
        //获得当前用户id
        long userId = BaseContext.getCurrent();

        //购物设置userId
        shoppingCart.setUserId(userId);

        //判断当前菜品或套餐是否已经存在
            //条件构造器
        LambdaQueryWrapper<ShoppingCart> wrapper = new LambdaQueryWrapper<>();
            //指定用户
        wrapper.eq(ShoppingCart::getUserId,userId);

        //若购物车里的是菜品
        if(shoppingCart.getDishId()!=null){
            //则查询菜品id是否存在
            wrapper.eq(ShoppingCart::getDishId,shoppingCart.getDishId());

        }else {
            //否则说明购物车里是套餐，查询套餐id
            wrapper.eq(ShoppingCart::getSetmealId,shoppingCart.getSetmealId());
        }


        ShoppingCart one = this.getOne(wrapper);
        //若购物车的菜品存在
        if (one!=null){
            //则在表中为该条数据的number字段+1
            Integer number = one.getNumber();
            one.setNumber(number+1);
            this.updateById(one);
        }else {
            //否则新增该条数据，设置数量为1，手动设置创建时间
            //为了返回数据的统一，用shoppingCart覆盖one
            shoppingCart.setNumber(1);
            shoppingCart.setCreateTime(LocalDateTime.now());
            this.save(shoppingCart);
            one=shoppingCart;
        }

        return one;
    }

    /**
     * 减少购物车
     * @param shoppingCart
     * @return
     */
    @Override
    public ShoppingCart sub(ShoppingCart shoppingCart) {
        //查询该菜品在购物车表中的数据
        LambdaQueryWrapper<ShoppingCart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ShoppingCart::getUserId,BaseContext.getCurrent());
        if (shoppingCart.getDishId()!=null){
            wrapper.eq(ShoppingCart::getDishId,shoppingCart.getDishId());
        }else {
            wrapper.eq(ShoppingCart::getSetmealId,shoppingCart.getSetmealId());
        }

        ShoppingCart cartOne = this.getOne(wrapper);
        Integer number = cartOne.getNumber();

        if (number==1){
            cartOne.setNumber(0);
            this.removeById(cartOne);
        }else{
            cartOne.setNumber(number-1);
            this.updateById(cartOne);
        }
        return cartOne;
    }

}
